from flask_migrate import Migrate, MigrateCommand
from flask_script import Manager
from info import create_app, db
from info.models import User

# 使用工厂函数创建app时,MySQL操作对象db也被初始化,关联配置类
app = create_app("dev")

# 创建脚本管理对象
manager = Manager(app)

# 让迁移和app db 建立连接
Migrate(app, db)

# 将脚本命令添加到脚本管理器
manager.add_command("mysql", MigrateCommand)


# 创建超级管理员用户
@manager.option("-u", "-username", dest="username")
@manager.option("-p", "-password", dest="password")
@manager.option("-m", "-mobile", dest="mobile")
def createsuperuser(username, password, mobile):
    """创建超级管理员用户"""
    if not all([username, password, mobile]):
        print("缺少参数, 格式: python manager.py createsuperuser -u username -p password -m mobile")
    else:
        # 创建用户模板对象
        user = User()
        user.nick_name = username
        user.password = password
        user.mobile = mobile
        user.is_admin = True
        try:
            db.session.add(user)
            db.session.commit()
        except Exception as e:
            print(e, "用户注册失败")
            db.session.rollback()


if __name__ == "__main__":
    manager.run()
